<template>
  <div class="app-container">
    <template v-if="!showConfigIndex">
      <div class="search-container">
        <el-form ref="form" :model="queryParams" :inline="true">
          <el-form-item prop="keywords" label="问卷名称">
            <el-input
              v-model="queryParams.keywords"
              placeholder="问卷名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <template #header>
          <el-button type="success" @click="openDialog()"
            ><i class="el-icon-circle-plus"></i> 新增</el-button>
          <el-button type="warning" @click="openUploadDialog()"
          ><i class="el-icon-circle-plus"></i> 上传问卷</el-button>
          <el-button
            type="danger"
            :disabled="ids.length === 0"
            @click="handleDelete()"
            ><i class="el-icon-delete"></i> 删除</el-button>
        </template>

        <el-table
          v-loading="loading"
          :data="dataList"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" width="55" prop="dataIndex"/>
          <el-table-column label="问卷名称" prop="name"/>
          <el-table-column label="创建时间" prop="createTimeText"/>
          <el-table-column label="更新时间" prop="updateTimeText"/>
          <el-table-column fixed="right" label="操作"  min-width="390" width="390">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                link
                @click="openQuestionIndexDialog(scope.row)"
              ><i class="el-icon-set-up"></i> 查看题目</el-button>
              <el-button
                type="primary"
                size="small"
                link
                @click="openQuestionsDialog(scope.row)"
              ><i class="el-icon-set-up"></i> 配置题目</el-button>
              <el-button
                type="warning"
                size="small"
                link
                @click="openDialog(scope.row.id)"
              ><i class="el-icon-edit"></i> 编辑</el-button>
              <!-- <el-button
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
              ><i class="el-icon-delete"></i> 删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-card>

    </template>
    <!-- 问卷表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="500px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="问卷名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入问卷名称" />
        </el-form-item>

        <el-form-item label="问卷描述" prop="describe">
          <el-input v-model="formData.describe" type="textarea" :autosize="{ minRows: 8}" placeholder="请输入描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :visible.sync="questionIndexVisible"
      :title="'【' + checkedSurvey.name + '】'"
      width="800px"
    >
      <el-form ref="questionForm" :form="answerForm" label-width="80px">
        <div v-for="(data, index) in details.questions" :key="data.id" style="margin-top: 10px; padding-left: 2%; padding-right: 2%;">
          <label>
            <span style="font-size: 16px;">{{(index + 1) + '、' + data.title}}</span>
            <span style="margin-left: 5px;">【{{ typeMap[data.type] }}】</span>
          </label>
          <div style="margin-top: 10px; padding-left: 2%; padding-right: 2%;">
            <template v-if="data.type == 'EXCLUSIVE_CHOICE'">
              <el-radio v-model="data.answer" v-for="(option) in data.options" :key="option.id" :label="option.id">{{option.title}}</el-radio>
            </template>
            <template v-if="data.type == 'MULTIPLE_CHOICE'">
              <el-checkbox v-model="data.answer" v-for="(option) in data.options" :key="option.id">{{option.title}}</el-checkbox>
            </template>
            <template v-if="data.type == 'TEXTAREA'">
              <el-input v-model="data.answer" placeholder="请输入内容"></el-input>
            </template>
          </div>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog width="400px" :visible.sync="uploadSurveyVisible"
      title="上传问卷">
      <p style="height: 50px;">当前仅支持excel导入，请下载excel模板，填入问卷内容后上传</p>
      <p style="margin-bottom: 10px; margin-top: 10px; height: 30px;"><a href="javascript:;" @click="downloadTemplate()">Excel模板下载</a></p>
      <el-upload
        class="upload-dialog"
        ref="upload"
        :action="uploadAction"
        :show-file-list="false"
        :on-change="submitUpload"
        :on-success="uploadFileSuccess"
        :headers="headers"
        :auto-upload="false">
        <el-button slot="trigger" style="margin-left: 5px;" type="success">上传问卷Excel文件</el-button>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
    </el-dialog>

    <surveyConfigIndex :checkedSurvey="checkedSurvey" v-if="showConfigIndex" @close="close"></surveyConfigIndex>

  </div>
</template>

<script>
import { Session } from '@/utils/storage'
import surveyApi from '@/api/aliyun/questionnaire/survey'
import { formatDate } from '@/utils/formatTime'
import surveyConfigIndex from '@/views/aliyun/questionnaire/survey/config'
export default {
	name: 'userIndex',
  components: {
    surveyConfigIndex
  },
	data() {
		return {
      answerForm: {},
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      checkedSurvey: {},
      dialog: {},
      formData: {},
      rules: {},
      typeMap: {
        EXCLUSIVE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TEXTAREA: '填空',
      },
      details: {},
      questionIndexVisible: false,
      uploadSurveyVisible: false,
      uploadAction: '',
      headers: {},

      showConfigIndex: false,
		};
	},
  mounted () {
    this.headers = {
      Authorization: 'Bearer ADMIN-TEMPLATE'
    };
  },
  methods: {
    close () {
      this.showConfigIndex = false;
    },
    downloadTemplate () {
      var a = document.createElement('a')
      a.href = process.env.VUE_APP_LOCAL_FILE_API_PREV + '/问卷题目上传模板.xlsx' 
      a.download = '问卷题目上传模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    uploadFileSuccess () {
      this.loading = false;
      this.uploadSurveyVisible = false;
      this.$message({message: '文件上传成功！', type: 'success'});
      this.handleQuery();
    },
    submitUpload () {
      this.loading = true;
      this.$refs.upload.submit();
    },
    openUploadDialog () {
      this.uploadSurveyVisible = true;
      console.log(process.env);
      if (process.env.NODE_ENV === 'production') {
        this.uploadAction = 'https://w66h994817.zicp.fun/platform/aliyun-api/survey/upload';
      } else {
        this.uploadAction = process.env.VUE_APP_BASE_API + '/aliyun-api/survey/upload';
      }
      
    },
    openQuestionIndexDialog (row) {
      this.questionIndexVisible = true;
      this.checkedSurvey = row;
      surveyApi.detail(row.id).then((res) => {
        this.details = res.data;
      });
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      surveyApi.page(params).then((res) => {
        let data = res.data;
        let index = 1;
        data.content.forEach(v => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        surveyApi.update(this.formData).then((res) => {
          this.$message({message: '问卷更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        surveyApi.add(this.formData).then((res) => {
          this.$message({message: '问卷添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },
    openQuestionsDialog(row) {
      this.showConfigIndex = true;
      this.checkedSurvey = row;
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑问卷');
        surveyApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;
        });
      } else {
        this.$set(this.dialog, 'title', '新增问卷');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该问卷, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (id) {
          surveyApi.delete(id).then((res) => {
            this.$message({message: '问卷删除成功！', type: 'success'});
            this.handleQuery();
          });
        } else {
          this.$message.error('暂不支持批量删除问卷！');
        }
      }).catch(() => {});
      
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>
<style scoped>
.surveyConfig /deep/ .el-dialog__body {
    height: 800px;
    overflow: auto;
}

.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
.el-table .warning-row {
  background: oldlace;
}
</style>